package com.tj.api.task;

import com.fqgj.common.utils.CollectionUtils;
import com.tj.bo.account.client.enums.DepositStatusEnum;
import com.tj.bo.account.server.dao.OrderDepositDao;
import com.tj.bo.account.server.entity.OrderDepositEntity;
import com.tj.bo.common.conf.config.RedisConfigUtil;
import com.tj.bo.common.conf.util.IpUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: binary-option
 * @description 超时任务
 * @author: frank
 * @create: 2020-09-07 17:15
 **/
@Component
public class DepositOrderTimeOutTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(DepositOrderTimeOutTask.class);
    @Autowired
    private RedisConfigUtil redisDbConfigUtil;
    @Autowired
    private OrderDepositDao orderDepositDao;

    /**
     * 关闭超时交易
     */
    @Scheduled(cron="0 0 0/1 * * ?")
    public void closeTimeoutDepositOrders(){
        String ip = IpUtils.getIp();
        String taskIp = redisDbConfigUtil.getTaskIp();
        if(!taskIp.equalsIgnoreCase(ip)){
            LOGGER.info("============ IP不匹配不执行任务 taskIp:{}, localIp:{}  ==========", taskIp, ip);
            return;
        }
        List<OrderDepositEntity> orderDepositEntities = orderDepositDao.selectsDepositOrderListByStatusAndTime(DepositStatusEnum.PROCESSING.getCode(), DateUtils.addDays(new Date(), -2));
        if(CollectionUtils.isEmpty(orderDepositEntities)){
            LOGGER.info("============ 超时关闭的充值列表为空 ==========", taskIp, ip);
            return;
        }
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for(OrderDepositEntity entity : orderDepositEntities){
            executorService.execute(() -> {
                try {
                    orderDepositDao.updateDepositStatus(entity.getDepositOrderNo(), DepositStatusEnum.FAILED.getCode());
                } catch (Exception e) {
                    LOGGER.error("========== 超时关闭的充值列表失败，depositOrderNo:{}, e =========" , entity.getDepositOrderNo(), e);
                }
            });
        }

    }
}
